<template>
  <q-page :padding="!$q.platform.is.mobile">

    <q-inner-loading visible v-if="model.noticeId < 0">
      <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading> 

    <!-- info -->
    <q-list-header class="row" v-if="model.noticeId>0">
        <span class="col">短信配置详情</span>
        <span v-if="model.status<=0" class="col-auto" @click="$router.push('/sms-code/edit/'+model.noticeId)">
          <q-icon name="mdi-settings" />
        </span>
    </q-list-header>
    <q-list separator class="q-py-none" :no-border="$q.platform.is.mobile" v-if="model.noticeId>0">
      <q-item>
        <q-item-side>短信标题：</q-item-side>
        <q-item-main>{{model.title}}</q-item-main>
      </q-item>
      <q-item>
        <q-item-side>发送渠道：</q-item-side>
        <q-item-main>{{ model.channel == 'ALIYUN' ? '阿里云' : (model.channel == 'ALIYUN_OLD' ? '阿里云(旧)' : '腾讯云') }}</q-item-main>
      </q-item>
      <q-item>
        <q-item-side>短信编码：</q-item-side>
        <q-item-main>{{model.config}}</q-item-main>
      </q-item>
      <q-item>
        <q-item-side>短信内容：</q-item-side>
        <q-item-main>{{model.content}}</q-item-main>
      </q-item>
    </q-list>
      
    <!-- user list -->
    <q-list-header class="row" v-if="users.length>0">
        <span class="col">手机号</span>
        <span class="col-auto" v-if="model.status==0&&users.length>0">(共 <b class="text-primary">{{users.length}}</b> 人)</span>
        <span class="col-auto" v-if="model.status>0&&nosend>0">(已发送:<b class="text-green">{{sended}}</b>人，未发送:<b class="text-primary">{{nosend}}</b>人)</span>
        <span class="col-auto" v-if="model.status>0&&nosend==0">(全部发送:<b class="text-green">{{sended}}</b>人)</span>
    </q-list-header>

    <q-list separator class="q-py-none" :no-border="$q.platform.is.mobile" v-if="users.length>0">
      <q-collapsible v-for="item in users" :key="'phone_'+item.userId">
        <template slot="header">
          <q-item-main>
            <q-item-tile label>{{item.userId}} <small v-if="item.userName">({{item.userName}})</small></q-item-tile>           
          </q-item-main>
          <q-item-side right>
            <span v-if="item.status==0"><small><b class="text-primary">未发送</b></small></span>
            <span v-if="item.status==1"><small><b class="text-green">已发送</b></small></span>
          </q-item-side>
        </template>
        <div>{{interceptor(item.userConfig)}}</div>
      </q-collapsible>
    </q-list>

    <!-- send -->
    <q-btn v-if="model.status==0&&test" color="secondary" class="fixed" icon="mdi-send" label="测试发送"
      :loading="loading" style="right: 15px; bottom: 15px" @click="testSend"/>

    <q-btn v-if="model.status==0&&!test" color="primary" class="fixed" icon="mdi-send" label="正式发送"
      :loading="loading" style="right: 15px; bottom: 15px" @click="send" />

    <q-btn v-if="model.status==1&&nosend>0" color="primary" class="fixed" icon="mdi-send" label="继续发送"
      :loading="loading" style="right: 15px; bottom: 15px" @click="send" />

  </q-page>
</template>

<script>
function _computeParamNames(tmpl) {
  let array = tmpl.split('${');
  let size = array.length;
  if(size == 1) {
    // 无参数
    return [];
  } else {
    try {
      let names = [];
      for(let i = 1; i < size; i++) {
        names.push(array[i].substring(0, array[i].indexOf('}')));
      }
      return names;
    } catch {
      return [];
    }
  }
};

export default {
  name: 'PageSmsCodeView',
  data() {
    return {
      loading: false,
      test: true,
      nosend: 0,
      sended: 0,
      model : {
        noticeId : -1,
        status: -1
      },
      users:[],
      paramNames: []
    }
  },
  mounted() {
    let me = this;
    me.loadModel(this.$route.params.id);
    me.loadUsers(this.$route.params.id);
    this.$api.ui.pageBackBtn = function(){
      me.$router.push('/sms-code');
    }
  },
  methods: {
    loadModel(id) {
      let me = this;
      this.$api.notice.loadOne(id, res=>{
        me.model = res.data.model;
        me.paramNames = _computeParamNames(res.data.model.content);
      });
    },
    loadUsers(id) {
      let me = this;
      this.$api.notice.loadUsers(id, res=>{
        me.users = res.data.model;
        me.nosend = 0;
        me.sended = 0;
        for(let i = 0; i < me.users.length; i++) {
          if(me.users[i].status <= 0) {
            me.nosend += 1;
          } else {
            me.sended += 1;
          }
        }
      });
    },
    send() {
      let me = this;
      let noticeId = me.model.noticeId;
      me.loading = true;
      me.$api.notice.sendSmsCode(noticeId, res=>{
        let ret = res.data.model;
        me.$q.notify({ message: '短信已发送，成功:' + ret.success + '，失败:' + ret.fail, type: 'positive' });
        me.loadUsers(noticeId);     
        me.model.status = 1;   
        me.loading = false;
      }, err=>{
        me.loadUsers(noticeId);
        me.loading = false;
      })
    },
    testSend() {
      let me = this;
      this.$q.dialog({
        title: '发送测试',
        message: '请输入接收测试短信的手机号码',
        prompt: { model: '', type: 'number' },
        cancel: true,
        color: 'secondary'
      }).then(data => {
        let tel = data - 0;
        if(isNaN(tel) || tel < 10000000000 || tel > 20000000000) {
          me.$q.notify({ message: '请输入合法的手机号', type: 'negative' });          
          return;
        } else {
          me.loading = true;
          me.$api.notice.testSmsCode(me.model.noticeId, tel, res=>{
            me.$q.notify({ message: '测试短信已成功发送', type: 'positive' });
            me.test = false;
            me.loading = false;
          }, err=>{
            me.loading = false;
          })
        }
      }).catch(() => {})
    },
    interceptor(configs) {
      let names = this.paramNames;
      let content = this.model.content;
      if(names.length <= 0) {
        return content;
      } else {
        let configArray = configs.split('@_@');
        for(let i = 0; i < names.length; i++) {
          content = content.replace('${'+names[i]+'}', configArray[i]);
        }
        return content;
      }
    }
  }
}
</script>

